﻿/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A
 * copy of the license can be found at http://go.microsoft.com/fwlink/?LinkID=131993. If
 * you cannot locate the Microsoft Public License, please send an email to
 * mixon@microsoft.com. By using this source code in any fashion, you are agreeing to
 * be bound by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System;
using System.Windows.Controls;

namespace MIXOnline.Descry
{
    /// <summary>
    /// The fundamental Panel that is animated horizontally on the Timeline
    /// These are contained by the VirtualizedTimelineItemsControl styled in the
    /// Themes/Generic.xaml.
    /// </summary>
    public partial class SurfacePanel : Grid
    {
        public SurfacePanel()
        {
            InitializeComponent();
        }

        TimeWindow _timeWindow = new TimeWindow();

        public TimeWindow TimeWindow
        {
            get { return _timeWindow; }
            set
            {
                _timeWindow = value;
                UpdateChildrenWithTimeWindow();
            }
        }

        public void UpdateChildrenWithTimeWindow()
        {
            // iterate through children if any and assigned updated TimeWindows
            int childrenCount = this.Children.Count / 2; //only half are VirtualizedTimeStackPanels

            long surfacePanelTicks = _timeWindow.WindowTimeSpan.Ticks;

            if (surfacePanelTicks == 0)
                throw new Exception("WindowTimeSpan has never been set, and must have a duration");

            if (childrenCount == 0)
                return; // no point in continuing if we do not have children

            // divide total TimeSpan by number of children
            TimeSpan columnTimeSpan = new TimeSpan(surfacePanelTicks / childrenCount);
            DateTime startingDateTime = _timeWindow.WindowStartTime;

            // update the children with the new DateTime Info
            foreach (object vtsp in this.Children)
            {
                if (vtsp is VirtualizedTimelineStackPanel)
                {
                    // increment StartTime for each VirtualizedTimeStackPanel
                    (vtsp as VirtualizedTimelineStackPanel).TimeWindow = new TimeWindow() { WindowStartTime = startingDateTime, WindowTimeSpan = columnTimeSpan };
                    startingDateTime += columnTimeSpan;
                }
            }
        }

    }
}
